import {
  addGoods,
  updateGoods,
  getGoods,
  uploadFile
} from '../../../services/good/index';
import {
  getCategoryList
} from '../../../services/category/index';
import {
  baseURL
} from '../../../services/request';
import Toast from 'tdesign-miniprogram/toast/index';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    categoryList: [],
    index: 0,
    priceArr: new Array(20),
    productName: '',
    productSpec: '',
    sortNo: '',
    site: 0,
    description: '',
    desc_long: '',
    desc_short: '',
    originuploadFiles: '',
    gridConfig: {
      column: 4,
      width: 160,
      height: 160,
    },
    id: '',
    uploadFiles: [],
    price1: '',
    price2: '',
    price3: '',
    price4: '',
    price5: '',
    price6: '',
    price8: '',
    price9: '',
    price10: '',
    price11: '',
    price12: '',
    price13: '',
    price14: '',
    price15: '',
    price16: '',
    price17: '',
    price18: '',
    price19: '',
    price20: '',
  },
  construstorFile(arr) {
    return arr.map((el) => {
      return {
        url: el,
        type: 'image',
      };
    });
  },

  // 图片上传
  handleSuccess(e) {
    const self = this;
    const tempOrigin = [];
    const role = wx.getStorageSync('role');
    const picType = e.currentTarget.dataset.type;
    const fileList = e.detail.files;
    this.setData({
      [picType]: [...this.data[picType], ...fileList],
    });
    //  多图统一上传
    fileList.forEach((el) => {
      wx.uploadFile({
        url: `${baseURL}fileserver/pt/fileserver/action/upload`,
        filePath: el.url,
        name: 'file',
        header: {
          devType: 4,
          userId: role.userId,
          token: role.tokenId,
          appId: 'crm_agent',
          authType: 'agent',
        },
        success: function (result) {
          if (JSON.parse(result.data).code == 200) {
            const resourceUrl = JSON.parse(result.data).data.urlPath;
            console.log(resourceUrl);
            tempOrigin.push(resourceUrl);
            self.setData({
              originuploadFiles: [...self.data.originuploadFiles, resourceUrl],
            });
          }
        },
      });
    });
  },
  // 移除图片

  handleRemove(e) {
    const {
      index
    } = e.detail;
    const picType = e.currentTarget.dataset.type;
    console.log(index, 'index', picType);
    const picTypeList = this.data[picType];
    this.data[picType].splice(index, 1);
    this.data.originuploadFiles.splice(index, 1);
    console.log(picTypeList, 'picTypeList');
    this.setData({
      [picType]: picTypeList,
      originuploadFiles: this.data.originuploadFiles,
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const {
      id
    } = options;
    this.getList(() => {
      if (id) {
        this.getGoodsView(id);
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},
  getGoodsView(id) {
    getGoods({
      kid: id,
    }).then((res) => {
      // todo 回显数据
      const {
        classifyId,
        price,
        price1,
        price2,
        price3,
        price4,
        price5,
        price6,
        price7,
        price8,
        price9,
        price10,
        price11,
        price12,
        price13,
        price14,
        price15,
        price16,
        price17,
        price18,
        price19,
        price20,
        desc_short,
        desc_long,
        picSmall,
        productName,
        productSpec,
        sortNo,
      } = res.data;
      const index = this.data.categoryList.findIndex((item) => item.kid === classifyId);
      const list = [];
      const originUrl = [];
      if (picSmall) {
        const temp = picSmall.split(',');
        for (let i = 0; i < temp.length; i++) {
          originUrl.push(temp[i]);
          list.push({
            url: temp[i],
            type: 'image',
            name: i,
          });
        }
      }
      this.setData({
        id,
        price: price,
        price1: price1,
        price2,
        price3,
        price4,
        price5,
        price6,
        price7,
        price8,
        price9,
        price10,
        price11,
        price12,
        price13,
        price14,
        price15,
        price16,
        price17,
        price18,
        price19,
        price20,
        productName: productName,
        productSpec: productSpec,
        sortNo: sortNo,
        desc_short,
        desc_long,
        picSmall,
        site: Number(index),
        uploadFiles: list,
        originuploadFiles: originUrl,
      });
    });
  },
  getList(cb) {
    getCategoryList({}).then((res) => {
      this.setData({
        categoryList: res.data,
      });
      setTimeout(() => {
        cb();
      });
    });
  },
  onInput1Value(e) {
    const {
      value
    } = e.detail;
    this.setData({
      price1: value,
    });
  },
  onInput2Value(e) {
    const {
      value
    } = e.detail;
    this.setData({
      price2: value,
    });
  },
  onInput3Value(e) {
    const {
      value
    } = e.detail;
    this.setData({
      price3: value,
    });
  },
  onInput4Value(e) {
    const {
      value
    } = e.detail;
    this.setData({
      price4: value,
    });
  },
  onInput5Value(e) {
    const {
      value
    } = e.detail;
    this.setData({
      price5: value,
    });
  },
  onInput6Value(e) {
    const {
      value
    } = e.detail;
    this.setData({
      price6: value,
    });
  },
  onInput7Value(e) {
    const {
      value
    } = e.detail;
    this.setData({
      price7: value,
    });
  },
  onInput8Value(e) {
    const {
      value
    } = e.detail;
    this.setData({
      price8: value,
    });
  },
  onInput9Value(e) {
    const {
      value
    } = e.detail;
    this.setData({
      price9: value,
    });
  },
  onInput10Value(e) {
    const {
      value
    } = e.detail;
    this.setData({
      price10: value,
    });
  },
  onInput11Value(e) {
    const {
      value
    } = e.detail;
    this.setData({
      price11: value,
    });
  },
  onInput12Value(e) {
    const {
      value
    } = e.detail;
    this.setData({
      price12: value,
    });
  },
  onInput13Value(e) {
    const {
      value
    } = e.detail;
    this.setData({
      price13: value,
    });
  },
  onInput14Value(e) {
    const {
      value
    } = e.detail;
    this.setData({
      price14: value,
    });
  },
  onInput15Value(e) {
    const {
      value
    } = e.detail;
    this.setData({
      price15: value,
    });
  },
  onInput16Value(e) {
    const {
      value
    } = e.detail;
    this.setData({
      price16: value,
    });
  },
  onInput17Value(e) {
    const {
      value
    } = e.detail;
    this.setData({
      price17: value,
    });
  },
  onInput18Value(e) {
    const {
      value
    } = e.detail;
    this.setData({
      price18: value,
    });
  },
  onInput19Value(e) {
    const {
      value
    } = e.detail;
    this.setData({
      price19: value,
    });
  },
  onInput20Value(e) {
    const {
      value
    } = e.detail;
    this.setData({
      price20: value,
    });
  },
  onInputNameValue(e) {
    const {
      value
    } = e.detail;
    this.setData({
      productName: value,
    });
  },
  onInputGuigeValue(e) {
    const {
      value
    } = e.detail;
    this.setData({
      productSpec: value,
    });
  },
  onInputOrtValue(e) {
    const {
      value
    } = e.detail;
    this.setData({
      sortNo: value,
    });
  },
  onInputlongDescValue(e) {
    const {
      value
    } = e.detail;
    this.setData({
      desc_long: value,
    });
  },
  onInputsortDescValue(e) {
    const {
      value
    } = e.detail;
    this.setData({
      desc_short: value,
    });
  },
  bindPickerChange(e) {
    this.setData({
      site: Number(e.detail.value),
    });
  },
  formSubmit() {
    const {
      id,
      price1,
      price2,
      price3,
      price4,
      price5,
      price6,
      price7,
      price8,
      price9,
      price10,
      price11,
      price12,
      price13,
      price14,
      price15,
      price16,
      price17,
      price18,
      price19,
      price20,
      productName,
      productSpec,
      sortNo,
      desc_short,
      desc_long,
      site,
    } = this.data;
    if (!productName) {
      Toast({
        selector: '#t-toast',
        message: '请填写产品名称',
        icon: '',
        duration: 1000,
      });
      return;
    }
    if (!productSpec) {
      Toast({
        selector: '#t-toast',
        message: '请填写商品规格',
        icon: '',
        duration: 1000,
      });
      return;
    }
    if (!sortNo) {
      Toast({
        selector: '#t-toast',
        message: '请填写商品序号',
        icon: '',
        duration: 1000,
      });
      return;
    }
    if (!price1) {
      Toast({
        selector: '#t-toast',
        message: '请填写价格1',
        icon: '',
        duration: 1000,
      });
      return;
    }
    if (!desc_short) {
      Toast({
        selector: '#t-toast',
        message: '商品短描述',
        icon: '',
        duration: 1000,
      });
      return;
    }
    if (!desc_long) {
      Toast({
        selector: '#t-toast',
        message: '商品长描述',
        icon: '',
        duration: 1000,
      });
      return;
    }
    if (!this.data?.originuploadFiles.length === 0) {
      Toast({
        selector: '#t-toast',
        message: '请上传图片',
        icon: '',
        duration: 1000,
      });
      return;
    }
    if (id) {
      updateGoods({
        price1,
        price2,
        price3,
        price4,
        price5,
        price6,
        price7,
        price8,
        price9,
        price10,
        price11,
        price12,
        price13,
        price14,
        price15,
        price16,
        price17,
        price18,
        price19,
        price20,
        classifyId: this.data.categoryList[site].kid,
        productName: productName,
        productSpec: productSpec,
        sortNo: sortNo,
        desc_short,
        desc_long,
        picSmall: this.data?.originuploadFiles && this.data?.originuploadFiles.join(','),
        productId: id,
      }).then((res) => {
        if (res.status) {
          wx.showToast({
            title: '编辑成功',
          });
          wx.navigateBack({
            delta: 1,
          });
        }
      });
    } else {
      addGoods({
        price1,
        price2,
        price3,
        price4,
        price5,
        price6,
        price7,
        price8,
        price9,
        price10,
        price11,
        price12,
        price13,
        price14,
        price15,
        price16,
        price17,
        price18,
        price19,
        price20,
        classifyId: this.data.categoryList[site].kid,
        productName: productName,
        productSpec: productSpec,
        sortNo: sortNo,
        desc_short,
        desc_long,
        picSmall: this.data?.uploadFiles && this.data?.uploadFiles.join(','),
      }).then((res) => {
        if (res.status) {
          wx.showToast({
            title: '创建成功',
          });
          wx.navigateBack({
            delta: 1,
          });
        }
      });
    }
  },
  async handleAdd() {
    const self = this;
    try {
      const tempFilePath = await new Promise((resolve, reject) => {
        wx.chooseImage({
          count: 10,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera'],
          success: (res) => {
            const {
              tempFilePaths
            } = res;
            resolve(tempFilePaths);
            // if (size <= 10485760) {
            //   resolve(path);
            // } else {
            //   reject({
            //     errMsg: '图片大小超出限制，请重新上传',
            //   });
            // }
          },
          fail: (err) => reject(err),
        });
      });
      const role = wx.getStorageSync('role');
      for (let index = 0; index < tempFilePath.length; index++) {
        const path = tempFilePath[index];
        wx.uploadFile({
          url: `${baseURL}fileserver/pt/fileserver/action/upload`,
          filePath: path,
          name: 'file',
          header: {
            devType: 4,
            userId: role.userId,
            token: role.tokenId,
            appId: 'crm_agent',
            authType: 'agent',
          },
          success: function (result) {
            if (JSON.parse(result.data).code == 200) {
              const resourceUrl = JSON.parse(result.data);
              var temp = self.data.uploadFiles;
              temp.push(resourceUrl.data.urlPath);
              self.setData({
                uploadFiles: temp,
              });
            }
          },
        });
      }
    } catch (error) {
      if (error.errMsg === 'chooseImage:fail cancel') return;
    }
  },
  onMoveTap(e) {
    const {
      index
    } = e.currentTarget.dataset;
    const {
      uploadFiles
    } = this.data;
    uploadFiles.splice(index, 1);
    this.setData({
      uploadFiles,
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
  onWithoutTitlePicker() {},
});